package com.modbus.tcp.utils;

import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.ip.IpParameters;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class Modbus4jTcpMaster {


//    private static ModbusFactory modbusFactory;
//
//    static {
//        if (modbusFactory == null) {
//            modbusFactory = new ModbusFactory();
//
//        }
//    }

    private ModbusFactory modbusFactory = null;

    public ModbusFactory getModbusFactory() {
        return modbusFactory;
    }


    /**
     * 获取master
     *
     * @return master
     */
    public  ModbusMaster getMaster() {
        IpParameters params = new IpParameters();
        params.setHost("127.0.0.1");
        params.setPort(30000);
        params.setEncapsulated(true);//这个属性确定了协议帧是否是通过tcp封装的RTU结构，采用modbus tcp/ip时，要设为false, 采用modbus rtu over tcp/ip时，要设为true
        if (modbusFactory == null) {
            modbusFactory = new ModbusFactory();
        }
        ModbusMaster master = modbusFactory.createTcpMaster(params, false);// TCP 协议
        try {
            //设置超时时间
            master.setTimeout(1000);
            //设置重连次数
            master.setRetries(3);
            //初始化
            master.init();
            log.info("modbusmaster connect slave success!");
        } catch (ModbusInitException e) {
            e.printStackTrace();
            log.error("modbusmaster connect slave fail, {}", e.getMessage());
        }
        return master;
    }

    /**
     * 获取master
     *
     * @return master
     */
    public  ModbusMaster getMaster(String ipAdd,int ipPort,boolean ifRtu) {
        IpParameters params = new IpParameters();
        params.setHost(ipAdd);
        params.setPort(ipPort);
        params.setEncapsulated(ifRtu);//这个属性确定了协议帧是否是通过tcp封装的RTU结构，采用modbus tcp/ip时，要设为false, 采用modbus rtu over tcp/ip时，要设为true
        if (modbusFactory == null) {
            modbusFactory = new ModbusFactory();
        }
       // ModbusMaster master = modbusFactory.createTcpMaster(params, false);// TCP 协议

        ModbusMaster master = modbusFactory.createTcpMaster(params, true);// TCP 协议
        try {
            //设置超时时间
            master.setTimeout(1000);
            //设置重连次数
            master.setRetries(3);
            //初始化
            master.init();
//            log.info("modbusmaster connect slave success!");
        } catch (ModbusInitException e) {
//            e.printStackTrace();
            log.error("modbusmaster connect slave fail, {}", e.getMessage());
        }
        return master;
    }
}
